package app.controller;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import app.config.Config;
import app.domain.FixOrder;
import app.domain.FixOrderHandle;
import app.domain.FixOrderInfo;
import app.domain.FixOrderPhoto;
import app.domain.FixOrderStatus;
import app.domain.Message;
import app.domain.Result;
import app.domain.UserInfo;
import app.service.FixOrderHandleService;
import app.service.FixOrderPhotoService;
import app.service.FixOrderService;
import app.service.FixOrderStatusService;
import app.service.MessageService;
import app.utils.DateUtil;

@Controller
@RequestMapping("fixOrder")
public class FixOrderController {
   public static Logger logger=LogManager.getLogger(FixOrderController.class);
	
	
   @Autowired
   private FixOrderService fixOrderService;
   @Autowired
   private FixOrderPhotoService fixOrderPhotoService;
   @Autowired
   private FixOrderStatusService fixOrderStatusService;
   @Autowired
   private MessageService messageService;
   @Autowired
   private FixOrderHandleService fixOrderHandleService;
   
   @RequestMapping("/addOrder")
   @ResponseBody
   public Result add(String article,String description,String photoStr,
		            Integer accountId,String name,String phone,String address,String remark){
	   Result result=new Result();
	   try{
		   //添加订单基本信息
		   FixOrder fixOrder=new FixOrder();
		   fixOrder.setArticle(article);
		   fixOrder.setDescription(description);
		   fixOrder.setAccountId(accountId);
		   fixOrder.setName(name);
		   fixOrder.setPhone(phone);
		   fixOrder.setAddress(address);
		   fixOrder.setRemark(remark);
		   //fixOrder.setStatus(Config.FIXORDER_STATUS_ONFIX);
		   fixOrder.setHandleStatus(Config.FIXORDER_HANDLE_STATUS_UN);
		   int fixOrderId=fixOrderService.addFixOrder(fixOrder);
		   //记录订单状态信息
		   FixOrderStatus fixOrderStatus=new FixOrderStatus();
		   fixOrderStatus.setFixOrderId(fixOrderId);
		   fixOrderStatus.setOperation("新增报修");
		   fixOrderStatus.setRemark("用户新建报修订单");
		   fixOrderStatusService.addStatusInfo(fixOrderStatus);
		   //向管理员发送订单创建提醒
		   String content="有新的报修订单，编号为："+fixOrderId;
		   Message message=new Message(content, Config.ADMIN_ACCOUNTID);
		   messageService.addMessage(message);
		   //添加订单图片信息
		   String[] photoIds=photoStr.split(",");
		   if(photoIds.length>0&&!photoStr.equals("")){
			   for(String photoId:photoIds){
				   FixOrderPhoto fixOrderPhoto=new FixOrderPhoto();
				   fixOrderPhoto.setFixOrderId(fixOrderId);
				   fixOrderPhoto.setPhotoId(Integer.parseInt(photoId));
				   fixOrderPhoto.setType(Config.ORDER_PHOTO_TYPE_USER);
				   fixOrderPhotoService.addFixOrderPhoto(fixOrderPhoto);
			   }
		   }
		   result.setCode(Config.SUCCESS_CODE);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   logger.warn("FixOrderController addNewOrder exception");
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   @RequestMapping("/updateOrder")
   @ResponseBody
   public Result add(Integer fixOrderId,String article,String description,String photoStr,
		            Integer accountId,String name,String phone,String address,String remark){
	   Result result=new Result();
	   try{
		   FixOrder fixOrder=new FixOrder();
		   fixOrder.setId(fixOrderId);
		   fixOrder.setArticle(article);
		   fixOrder.setDescription(description);
		   fixOrder.setAccountId(accountId);
		   fixOrder.setName(name);
		   fixOrder.setPhone(phone);
		   fixOrder.setAddress(address);
		   fixOrder.setRemark(remark);
		   fixOrder.setHandleStatus(Config.FIXORDER_HANDLE_STATUS_UN);
		   fixOrderService.updateInfo(fixOrder);
		   String[] photoIds=photoStr.split(",");
		   if(photoIds.length>0&&!photoStr.equals("")){
			   for(String photoId:photoIds){
				   FixOrderPhoto fixOrderPhoto=new FixOrderPhoto();
				   fixOrderPhoto.setFixOrderId(fixOrderId);
				   fixOrderPhoto.setPhotoId(Integer.parseInt(photoId));
				   fixOrderPhoto.setType(Config.ORDER_PHOTO_TYPE_USER);
				   fixOrderPhotoService.addFixOrderPhoto(fixOrderPhoto);
			   }
		   }
		  //记录订单状态信息
		   FixOrderStatus fixOrderStatus=new FixOrderStatus();
		   fixOrderStatus.setFixOrderId(fixOrderId);
		   fixOrderStatus.setOperation("信息更新");
		   fixOrderStatus.setRemark("用户更新了报修信息");
		   fixOrderStatusService.addStatusInfo(fixOrderStatus);
		   
		   //向管理员发送订单信息修改提醒
		   String content="编号为："+fixOrderId+"的报修信息已被更改";
		   Message message=new Message(content, Config.ADMIN_ACCOUNTID);
		   messageService.addMessage(message);
		   
		   result.setCode(Config.SUCCESS_CODE);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   logger.warn("FixOrderController updateOrder exception");
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   @RequestMapping(value="/list",method=RequestMethod.GET)
   @ResponseBody
   public Result orderList(Integer fixOrderId,Integer accountId,Integer handleStatus,String dateStart,String dateEnd){
	   Result result=new Result();
	   List<FixOrder> list=new ArrayList<>();
	   try{
		   Timestamp time1=null;
		   Timestamp time2=null;
		   java.util.Date date1=DateUtil.StringToDate(dateStart,"yyyy-MM-dd HH:mm");
		   java.util.Date date2=DateUtil.StringToDate(dateEnd,"yyyy-MM-dd HH:mm");
		   if(date1!=null)
			   time1=new Timestamp(date1.getTime());
		   if(date2!=null)
			   time2=new Timestamp(date2.getTime());
		   list=fixOrderService.getByRequire(fixOrderId,accountId,handleStatus,time1,time2);  
	       result.setCode(Config.SUCCESS_CODE);
	       result.setRow(list);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   @RequestMapping("/delete/{id}")
   @ResponseBody
   public Result delete(@PathVariable("id")int id){
	   Result result=new Result(Config.SUCCESS_CODE,"");
	   try{
		   fixOrderService.delete(id);
		  //记录订单状态信息
		   FixOrderStatus fixOrderStatus=new FixOrderStatus();
		   fixOrderStatus.setFixOrderId(id);
		   fixOrderStatus.setOperation("取消报修");
		   fixOrderStatus.setRemark("用户取消了报修");
		   fixOrderStatusService.addStatusInfo(fixOrderStatus);
		   //向管理员和工人发送订单取消
		   FixOrderHandle handleInfo=fixOrderHandleService.getByFixOrderId(id);
		   String contentToAdmin="编号为："+id+"的报修订单已被取消";
		   String contentToWorker="编号为："+id+"的报修订单已被取消";
		   Message message1=new Message(contentToAdmin, Config.ADMIN_ACCOUNTID);
		   Message message2=new Message(contentToWorker,handleInfo.getRepairerId());
		   messageService.addMessage(message1);
		   messageService.addMessage(message2);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   //管理员关闭订单
   @RequestMapping("/closeByAdmin/{id}")
   @ResponseBody
   public Result closeByAdmin(@PathVariable("id")int fixOrderId,int userId){
	   Result result=new Result(Config.SUCCESS_CODE,"");
	   try{
		   fixOrderService.closeOrder(fixOrderId);
		   //记录订单状态信息
		   FixOrderStatus fixOrderStatus=new FixOrderStatus();
		   fixOrderStatus.setFixOrderId(fixOrderId);
		   fixOrderStatus.setOperation("关闭订单");
		   fixOrderStatus.setRemark("订单处理完成，管理员关闭了该订单");
		   fixOrderStatusService.addStatusInfo(fixOrderStatus);
		   
		   FixOrderHandle handleInfo=fixOrderHandleService.getByFixOrderId(fixOrderId);
		   //向住户和工人发送订单关闭提醒
		   String contentToUser="编号为："+fixOrderId+"的报修订单已被管理员关闭";
		   String contentToWorker="编号为："+fixOrderId+"的报修订单已被管理员关闭";
		   Message message1=new Message(contentToUser, userId);
		   Message message2=new Message(contentToWorker, handleInfo.getRepairerId());
		   messageService.addMessage(message1);
		   messageService.addMessage(message2);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   //工人关闭订单
   @RequestMapping("/closeByWorker/{id}")
   @ResponseBody
   public Result closeByWorker(@PathVariable("id")int id,int userId){
	   Result result=new Result(Config.SUCCESS_CODE,"");
	   try{
		   fixOrderService.closeOrder(id);
		   //记录订单状态信息
		   FixOrderStatus fixOrderStatus=new FixOrderStatus();
		   fixOrderStatus.setFixOrderId(id);
		   fixOrderStatus.setOperation("关闭订单");
		   fixOrderStatus.setRemark("订单处理完成，维修工人关闭了该订单");
		   fixOrderStatusService.addStatusInfo(fixOrderStatus);
		  //向管理员和住户发送订单关闭提醒
		   String contentToAdmin="编号为："+id+"的报修订单已被工人关闭";
		   String contentToUser="编号为："+id+"的报修订单已被工人关闭";
		   Message message1=new Message(contentToAdmin, Config.ADMIN_ACCOUNTID);
		   Message message2=new Message(contentToUser, userId);
		   messageService.addMessage(message1);
		   messageService.addMessage(message2);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
   @RequestMapping(value="/getInfo",method=RequestMethod.GET)
   @ResponseBody
   public Result getInfo(int fixOrderId){
	   Result result=new Result(Config.SUCCESS_CODE,"");
	   try{
		   FixOrderInfo fixOrderInfo=fixOrderService.getInfo(fixOrderId);
		   result.setRow(fixOrderInfo);
	   }
	   catch(Exception e){
		   e.printStackTrace();
		   result.setCode(Config.FAIL_CODE);
		   return result;
	   }
	   return result;
   }
   
    //工人获取所属订单
 	@RequestMapping("/getByWorker/{workerId}")
 	@ResponseBody
 	public Result getWorkerOrder(@PathVariable(value="workerId")Integer workerId,Integer fixOrderId,Integer handleStatus){
 		Result result=new Result(Config.SUCCESS_CODE,"");
 		try{
 			List<FixOrder> list=fixOrderService.getByRequire(workerId,fixOrderId,handleStatus);
 			result.setRow(list);
 		}
 		catch(Exception e){
 			e.printStackTrace();
 			result.setCode(Config.FAIL_CODE);
 			return result;
 		}
 		return result;
 	}
   
}
